网页内容复制黏贴

对网页上的内容实现复制粘贴的功能

痛点:需要支持多种不同的浏览器 主要有IE,Firefox

  1. IE浏览器下的解决方案:
    window.clipboardData.setData("Text", text);
  2. 通用浏览器的解决方案:
    选中元素之后执行:
    document.execCommand('copy')
  3. Firefox下的解决方案
    两种折中的方案
    a. 监听hover事件 当鼠标移动至需要复制的文本上时 用户按下ctrl+c 实现复制
    b.window.prompt("Copy to clipboard: Ctrl+C, Enter", text); 弹出框内容为选中的文案,用户按下ctrl+c 实现复制

整合之后的代码为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
function copyToClipboard(text) {
if (window.clipboardData) { // Internet Explorer
window.clipboardData.setData("Text", text);
} else {
var textArea = document.createElement("textarea");
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
if (!document.execCommand('copy')) {
copyToClipboardMozilla(text);
} else {
showInfo("提示", "复制成功")
}

} catch (err) {
console.log('Oops, unable to copy');
}
document.body.removeChild(textArea);
}
}

function copyToClipboardMozilla(text) {
window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}

$(".copy").on("mouseenter", function () {
$(this).css("background-color", "#c8c9c8");
$(this).focus();
var textArea = document.createElement("textarea");
textArea.style.background = 'transparent';
textArea.id = "copyContent";
textArea.value = $(this).text();
document.body.appendChild(textArea);
textArea.select();
})

$(".copy").on("mouseleave", function () {
$(this).css("background-color", "");
document.body.removeChild(document.getElementById("copyContent"));
})


参考资料:

  1. 几个通用的解决复制的方法
  2. document.execCommand API
    W3C API
  3. How do I copy to the clipboard in JavaScript?
  4. How does Trello access the user’s clipboard?
  5. 20 行 JS 代码,实现复制到剪贴板功能
lemon wechat
欢迎大家关注我的订阅号 SeeMoonUp
写的不错?鼓励一下?不差钱?